var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var WxParse = require('../../wxParse/wxParse.js');
var base64 = require('../../utils/Base64.js');
var topictitle = "";
var topicid = "";
var app = getApp();
var uid = '';
var uname = ''; //作者用户名
var wxAuthFail = true;
var inviteuid = 0;
var linkcode = '';

var detailMessage = '';

Page({
  data: {
    util: util,

    indicatorDots: true,
    autoplay: true,
    interval: 4000,
    duration: 600,
    swiper_w: 0,
    swiper_h: 0,

    video_w: 300,
    video_h: 165,


    data: {},
    likeuser: [],
    detailMessage: '',

    isLiked: false, //是否已赞
    uid: '', //当前登录用户Id
    token: '', //post请求时，当前登录用户token
    loginUname: '', //当前登录用户名
    commentMsg: '',
    replyid: 0, //当前被回复的评论id
    openid: '',
    topicid: 0,

    hasShare: false,
    tuid: 0,
    firstImgUrl: '',

    isShow: false,

    isIphoneX: false,

    isOnLoad: false,


    contact_phone: '',

    commentList: [],
    colorSet: '',


    hide_commentview: true,
    pageIndex: "/pages/index/index",

    showNav: true,
  },

  onLoad: function(data) {

    var that = this;

    wx.showLoading({
      title: '加载中',
      mask: 'true'
    });

    //获取绑定小程序信息
    app.GetUserInfo(util.orgid, function(res){
      console.log("绑定小程序信息：", res);
      wx.setNavigationBarTitle({
        title: res.uname,
      })
    });

    //初始化底部导航
    var b_nav_data = app.getBottomNavData('detail/detail', function(data) {
      that.setData({
        bottom_nav_data: data,
        nav_bgColor: data[0].bgcolor,
        showNav: (data.shownav == 'false' ? false : true)
      });
    });
    //获取颜色配置
    app.getColorSetData(function(color) {
      that.setData({
        colorSet: color
      })
      that.resetNavColor();
    });

    wx.getSystemInfo({
      success: function(res) {
        var isiPhoneX = (res.model.indexOf('iPhone X') >= 0);
        // var height = res.windowWidth * 2 / 3;
        var height = res.windowWidth;
        var v_w = res.windowWidth;
        // v_w =  v_w - 25;
        var v_h = v_w * 4 / 7;
        that.setData({
          isiPhoneX: isiPhoneX,
          swiper_w: res.windowWidth,
          swiper_h: height,
          video_w: v_w,
          video_h: v_h,
          goodsImgView_h: (res.windowWidth - 30) / 2,
          windowWidth: res.windowWidth,
          windowHeight: res.windowHeight
        });
      }
    })


    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "wxcheck",
        "tc": that.data.tc
      },
      success: function(responseData) {
        console.log("==kankanshishenm====", responseData);
        that.setData({
          isShow: responseData.data.isShow
        });
      }
    });

    topicid = data.topicid ? data.topicid : util.detailId;

    //是否是从 别人分享的 页面点进来的
    inviteuid = data.inviteuid ? data.inviteuid : '';
    this.setData({
      hasShare: true,
      topicid: topicid,
      isOnLoad: true
    })

    //调用应用实例的方法获取全局数据
    that.getLoginInfo();

    var showcomments = data.showcomments || "";
    
    //获取关于等信息
    app.getAllAbout('contact', function (res) {
      that.setData({
        showcomments: showcomments,
        contact_phone: res
      })
    });
  },

  onShow: function() {

  },


  load: function() {
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "topicdetail",
      linkcode: linkcode,
      inviteuid: inviteuid,
      loginuid: that.data.uid ? that.data.uid : '',
      topicid: topicid,
      tc: that.data.tc
    };
    console.log("动态详情请求参数：", params);
    //动态详情
    util.api({
      data: params,
      success: function(responseData) {
        var data = responseData.data;
        console.log("啊啊啊啊啊详情：", data);

        //处理时间
        var date = new Date(data.dateline * 1000);
        data.formatDate = date.getFullYear() + "-" + (Number(date.getMonth()) + 1) + "-" + date.getDate();

        //处理视频
        if (data.video) {
          var videolinks = data.video.split(",");
          var len = videolinks.length;
          var tx_videolinks = [];
          for (var i = 0; i < len; i++) {
            if (videolinks[i].indexOf('v.qq.com') > 0) {
              tx_videolinks = tx_videolinks.concat(videolinks[i])
            }
          }
          len = tx_videolinks.length;
          var videoSrcs = new Array(len);
          var count = 0;
          for (var i = 0; i < len; i++) {
            app.getVideoSrcLink(i, tx_videolinks[i], function(url, index) {
              count++;
              if (url != -1) {
                videoSrcs[index] = url;
              }
              if (count >= len) {
                var videoSrcArr = [];
                for (var n = 0; n < len; n++) {
                  if (videoSrcs[n]) {
                    videoSrcArr = videoSrcArr.concat(videoSrcs[n]);
                  }
                }
                that.setData({
                  videolinkArray: videoSrcArr
                });
              }

            });
          }
        }
        var latitude = wx.getStorageSync('lat')
        var longitude = wx.getStorageSync('lon')
        var distanStr;
        if (latitude && longitude) {
          var distan = app.getDistance(latitude, longitude, data.lat, data.lon);
          if (distan > 1000) {
            distanStr = (distan / 1000).toFixed(2) + 'km';
          } else {
            distanStr = distan.toFixed(0) + 'm';
          }
          data.distanse = distanStr;

        }

        //处理message  
        detailMessage = data.message;
        // detailMessage = data.message.replace(/\n/g, '<br />');
        // console.log("detailMessage: ", detailMessage);

        that.setData({
          detailMessage: data.message,
        });
        /** 
         * WxParse.wxParse(bindName , type, data, target,imagePadding) 
         * 1.bindName绑定的数据名(必填) 
         * 2.type可以为html或者md(必填) 
         * 3.data为传入的具体数据(必填) 
         * 4.target为Page对象,一般为this(必填) 
         * 5.imagePadding为当图片自适应是左右的单一padding(默认为0,可选) 
         */
        WxParse.wxParse('detailMessage', 'html', detailMessage, that, 12);
        // data.message = data.message.replace(/&nbsp;/g, '');

        topictitle = data.topictitle;
        uname = data.user.username;

        var f_imgUrl = '';
        if (data.photoscbk && data.photoscbk.length > 0) {
          var firstImageInfo = data.photoscbk[0];
          if (firstImageInfo) {
            f_imgUrl = firstImageInfo.photo + "!120a";
          }
        }
        console.log("第一张图片链接：", f_imgUrl);
        that.setData({
          data: data,
          likeuser: data.likeuser,
          isLiked: data.isLiked,
          tuid: data.postuid,
          firstImgUrl: f_imgUrl
        });

        //当前用户是否已赞该动态
        that.isLike(uid);
        wx.hideLoading();

        that.loadTopicCommentList(that.data.topicid, 1);
      }
    });

    this.loadCommentList(topicid, 1);

  },

  //读取所有评论
  loadCommentList: function(gid, page) {
    var that = this;
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "ordercommentall",
        goods_id: gid,
        page: page,
        num: 10
      },
      success: function(responseData) {
        var data = responseData.data;
        console.log("商品评论：", data);
        if (data && data.length > 0) {
          data.forEach(function(m, i) {
            m.pinglun.date = util.formatTime(new Date(parseInt(m.pinglun.dateline) * 1000), '-', ':');
          });
          that.setData({
            commentList: data
          });
        }
      }
    });
  },
  //读取动态页所有评论
  loadTopicCommentList: function(topicid, page) {
    var that = this;
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "topiccommentlist",
        id: topicid,
        page: page,
        num: 10
      },
      success: function(responseData) {
        var data = responseData.data;
        console.log("商品评论topiccommentlist：", data);
        if (data && data.length > 0) {
          data.forEach(function(m, i) {
            m.date = util.formatTime(new Date(parseInt(m.dateline) * 1000), '-', ':');
          });
          that.setData({
            commentList: data
          });
        }
      }
    });
  },

  //重新读取 登录用户信息
  reGetUserInfo: function(e) {
    var that = this;
    console.log("reGetUserInfo: ", e);
    if (e == 1) {
      that.getLoginInfo();
    }
  },
  getLoginInfo: function() {
    var that = this;
    app.LoginUserInfo(function(res) {
      if (res && res != -1) {

        //更新数据
        wxAuthFail = false;
        uid = res.uid;
        that.setData({
          uid: res.uid,
          token: res.token,
          loginUname: res.uname,
          openid: res.wxsmall_openid
        })

        that.load();
        var canEdit = false;
        if (that.data.data && that.data.data.user && res.uid == that.data.data.user.uid) {
          canEdit = true;
        }
        //设置用户信息
        app.GetUserInfo(res.uid, function(u_res) {
          console.log("getUserInfo:", u_res);
          //更新数据
          that.setData({
            canEdit: canEdit ? canEdit : u_res.isgroup == 1
          })
        });
      } else {
        that.load();
        wxAuthFail = true;
      }
    }, inviteuid)
  },




  //是否已赞
  isLike: function(uid) {
    var that = this;
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "isliketopic",
        uid: uid,
        topicid: topicid
      },
      success: function(responseData) {
        var data = responseData.data;
        if (data.res === true) {
          that.setData({
            isLiked: true
          });
        }
      }
    });
  },

  //赞列表
  getZanList: function() {
    var that = this;
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "topiclikeuser",
        topicid: that.data.data.id,
        cuid: uid,
        page: 1,
        num: 100
      },
      success: function(responseData) {
        var data = responseData.data;
        console.log("赞列表数据：", data);
        if (!data.msg) {
          that.setData({
            likeuser: data
          });
        } else {
          that.setData({
            likeuser: []
          });
        }
      }
    });
  },

  //赞
  addLike: function(e) {
    if (wxAuthFail) {
      app.reAuthorize(this.reGetUserInfo);
      return;
    }

    var that = this;
    var uid = e.currentTarget.dataset.uid;
    var token = e.currentTarget.dataset.token;
    var privatekey = utilMd5.hexMD5(uid + 'liketopic' + token);
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "liketopic",
        uid: uid,
        topicid: topicid,
        privatekey: privatekey
      },
      method: 'POST',
      success: function(responseData) {
        var data = responseData.data;
        console.log("赞动作结果：", data);
        if (data.res === true) {
          that.setData({
            isLiked: true
          });
          app.dialog(that.data.tc == 1 ? '贊成功' : '赞成功', 'success', that.getZanList());
        } else {
          app.dialog(that.data.tc == 1 ? '贊失敗' : '赞失败', 'loading');
        }
      }
    });
  },
  //取消赞
  cancelLike: function(e) {
    var that = this;
    var uid = e.currentTarget.dataset.uid;
    var token = e.currentTarget.dataset.token;
    var privatekey = utilMd5.hexMD5(uid + 'delliketopic' + token);
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "delliketopic",
        uid: uid,
        topicid: topicid,
        privatekey: privatekey
      },
      method: 'POST',
      success: function(responseData) {
        var data = responseData.data;
        if (data.res === true) {
          that.setData({
            isLiked: false
          });
          app.dialog(that.data.tc == 1 ? '取消贊成功' : '取消赞成功', 'success', that.getZanList());
        } else {
          app.dialog(that.data.tc == 1 ? '取消贊失敗' : '取消赞失败', 'loading');
        }
      }
    });
  },
  //评论
  inputMessage: function(e) {
    //把评论内容绑定到提交按钮上
    var val = e.detail.value;
    this.setData({
      commentMsg: val
    })
  },
  changeReplyid: function(e) {
    var val = e.currentTarget.dataset.id;
    var replyusername = e.currentTarget.dataset.uname;
    this.setData({
      replyid: val,
      commentMsg: this.data.tc == 1 ? '@回復' : '@回复' + replyusername + ':'
    })
  },


  inputFinish: function(e) {
    var comment = e.detail.value;
    console.log("输入信息：" + comment);
    this.setData({
      commentValue: comment
    })
  },
  showCommentView: function(e) {
    this.setData({
      hide_commentview: false,
      data_id: e.currentTarget.dataset.id
    })
  },
  hideCommentView: function() {
    this.setData({
      hide_commentview: true
    })
  },
  addComment: function(e) {
    if (wxAuthFail) {
      app.reAuthorize(this.reGetUserInfo);
      return;
    }

    var that = this;
    var uid = e.currentTarget.dataset.uid ? e.currentTarget.dataset.uid : that.data.uid;
    var token = e.currentTarget.dataset.token ? e.currentTarget.dataset.token : that.data.token;
    var catatype = e.currentTarget.dataset.catatype;
    var replyid = e.currentTarget.dataset.replyid;
    var message = e.currentTarget.dataset.message ? e.currentTarget.dataset.message : that.data.commentValue;
    if (!message) {
      app.dialog(that.data.tc == 1 ? '請輸入內容' : '请输入内容', 'loading');
      return;
    }
    var privatekey = utilMd5.hexMD5(uid + 'topiccomment' + token);
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "topiccomment",
        uid: uid,
        id: topicid,
        type: catatype,
        replyid: replyid,
        message: message,
        privatekey: privatekey
      },
      method: 'POST',
      success: function(responseData) {
        var data = responseData.data;
        var txt = replyid > 0 ? (that.data.tc == 1 ? '回復' : '回复') : (that.data.tc == 1 ? '評論' : '评论');
        if (data.msg === "true") {
          that.setData({
            isLiked: true
          });
          that.setData({
            commentMsg: ''
          })

          app.dialog(txt + that.data.tc == 1 ? '成功' : '成功', 'success', that.refreshPage());
        } else {
          app.dialog(txt + that.data.tc == 1 ? '失敗' : '失败', 'loading');
        }
      }
    });
  },


  //页面分享
  onShareAppMessage: function() {
    var invUid = this.data.uid ? this.data.uid : '';
    var linkcode = this.data.data.linkcode ? this.data.data.linkcode : linkcode;
    var showcomments = this.data.showcomments || ''
    var path = '/pages/detail/detail?topicid=' + topicid + '&inviteuid=' + invUid + "&linkcode=" + linkcode + "&showcomments=" + showcomments;
    console.log("分享给好友：" + path);
    var title = topictitle ? topictitle : uname;
    return {
      title: title,
      path: path
    };
  },

  copyLink: function() {
    var that = this;
    wx.setClipboardData({
      data: that.data.data.alt,
      success: function(res) {
        wx.showToast({
          title: that.data.tc == 1 ? '已復制到剪貼板' : '已复制到剪贴板',
        })
      }
    })
  },


  showEWM: function(e) {
    wx.previewImage({
      current: e.currentTarget.dataset.imgsrc,
      urls: [e.currentTarget.dataset.imgsrc]
    })
  },
  //刷新当前页
  refreshPage: function() {
    wx.redirectTo({
      url: '/pages/detail/detail?topicid=' + topicid
    })
  },

  //跳转
  goAtherPage: function(e) {
    var url = e.currentTarget.dataset.link;
    //如果是 立即购买 或 咨询 则需要判断是否已授权登录
    if (wxAuthFail && (url.indexOf('order-confirm') >= 0)) {
      app.reAuthorize(this.reGetUserInfo);
      return;
    }

    var pageIndex = getCurrentPages().length;
    if (pageIndex >= 5) {
      wx.redirectTo({
        url: url,
        fail: function(e) {
          console.log(e)
        }
      })
    } else {
      wx.navigateTo({
        url: url,
        fail: function(e) {
          console.log(e)
        }
      })
    }
  },
  
  clickImg: function(e) {
    this.setData({
      "stv.src": e.currentTarget.dataset.imgsrc,
      "stv.display": "true"
    });
  },
  goAtherPageRedirect: function(e) {
    var url = e.currentTarget.dataset.link;
    wx.redirectTo({
      url: url
    })
  },
  //跳转
  goAtherPageRelaunch: function(e) {
    var url = e.currentTarget.dataset.link;
    //如果是 立即购买 或 咨询 则需要判断是否已授权登录
    if (wxAuthFail && (url.indexOf('gouwuche/gouwuche') >= 0)) {
      app.reAuthorize(this.reGetUserInfo);
      return;
    }
    if (util.orgid == '12545') {
      wx.navigateTo({
        url: url
      });
    } else {
      wx.reLaunch({
        url: url
      });

    }
  },
  clickImg: function(e) {
    // this.setData({
    //     "stv.src":e.currentTarget.dataset.imgsrc,
    //     "stv.display":"true"
    // });
    var imgListType = e.currentTarget.dataset.imglist;
    var imgList = [];
    if (imgListType == "1") {
      var photo = this.data.data.photoscbk;
      for (var i = 0; i < photo.length; i++) {
        imgList = imgList.concat([photo[i].photo]);
      }
    } else if (imgListType == "2") {
      var photo = this.data.data.link_works;
      for (var i = 0; i < photo.length; i++) {
        imgList = imgList.concat(photo[i].photosData);
      }
    } else if (imgListType == "3") {
      var photo = this.data.data.link_relations;
      for (var i = 0; i < photo.length; i++) {
        imgList = imgList.concat(photo[i].photosData);
      }
    }
    console.log(imgList);
    wx.previewImage({
      current: e.currentTarget.dataset.imgsrc,
      urls: imgList
    })
  },

  submitFormId: function(e) {
    app.saveFormId(e.detail.formId);

    var path = e.detail.value.nav_path;
    if (path && path.indexOf('navto:') == 0) {
      var navPath = path.slice(6);
      wx.navigateTo({
        url: navPath,
      })
    } else {
      wx.redirectTo({
        url: path
      });
    }
  },


  //删除数据
  delDataAction: function() {
    this.setData({
      modalHidden: false,
    })
  },

  deleteData: function() {

    var that = this;

    var uid = this.data.uid; //用户id
    var token = this.data.token; //用户token
    var privatekey = utilMd5.hexMD5(uid + 'deltopic' + token); //私钥
    var ownerId = this.data.data.user.uid;
    var params = {
      ac: "deltopic",
      privatekey: privatekey,
      uid: ownerId,
      edituid: uid,
      topicid: that.data.data.id
    }
    console.log("deltopic params: ", params);
    util.api({
      method: "POST",
      data: params,
      success: function(responseData) {

        var result = responseData.data;
        console.log("删除数据：", result);
        if (result.res) {
          app.dialogToast(that.data.tc == 1 ? '刪除成功' : "删除成功", 'success', function() {
            // wx.reLaunch({
            //   url: '/pages/index/index',
            // })
            wx.navigateBack({
              delta: 1
            })
          });
        }
      }
    });
  },

  showEWMAV: function(e) {
    wx.previewImage({
      current: e.currentTarget.dataset.imgsrc,
      urls: [e.currentTarget.dataset.imgsrc]
    })
  },

  makeCallPhone: function(e) {
    var phoneNum = e.currentTarget.dataset.number;
    console.log("phoneNum:" + phoneNum);
    wx.makePhoneCall({
      phoneNumber: phoneNum,
      success: function(e) {
        console.log("make call success:", JSON.stringify(e));
      },
      fail: function(e) {
        console.log("make call fail:", JSON.stringify(e));
      }
    })
  },

  resetNavColor: function() {
    var bg_color = '#d8202d';
    var fg_color = '#ffffff';
    if (this.data.colorSet) {
      var colorJO = this.data.colorSet;
      bg_color = colorJO.titlebg;
      fg_color = colorJO.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })

    this.setData({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },

  goMapView: function(e) {
    var addr = e.currentTarget.dataset.addr;
    var lat = parseFloat(addr.lat);
    var lon = parseFloat(addr.lon);
    wx.openLocation({
      latitude: lat,
      longitude: lon,
      scale: 20,
      name: addr.name,
      address: addr.address
    })
  },

})